package com.ruoyi.project.monitor.online.controller;

import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.constant.BusinessType;
import com.ruoyi.framework.session.SessionService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.monitor.online.domain.UserOnline;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 在线用户监控
 *
 * @author ruoyi
 */
@Controller
@RequestMapping("/monitor/online")
public class UserOnlineController extends BaseController {
  private String prefix = "monitor/online";

  @Autowired
  private SessionService sessionService;

  @Autowired
  private SessionDAO sessionDAO;

  @RequiresPermissions("monitor:online:view")
  @GetMapping()
  public String online() {
    return prefix + "/online";
  }

  @RequiresPermissions("monitor:online:list")
  @PostMapping("/list")
  @ResponseBody
  public TableDataInfo list(UserOnline userOnline) {
    startPage();
    List<UserOnline> list = sessionService.list();
    return getDataTable(list);
  }

  @RequiresPermissions("monitor:online:batchForceLogout")
  @Log(title = "在线用户", action = BusinessType.FORCE)
  @PostMapping("/batchForceLogout")
  @ResponseBody
  public AjaxResult batchForceLogout(@RequestParam("ids[]") String[] ids) {
    for (String sessionId : ids) {
      try {
        Session session = sessionDAO.readSession(sessionId);
      } catch (UnknownSessionException e) {
        return error("用户已下线");
      }


      if(sessionId.equals(ShiroUtils.getSessionId())) {
        return error("当前登陆用户无法强退");
      }
      sessionService.forceLogout(sessionId);
    }
    return success();
  }

  @RequiresPermissions("monitor:online:forceLogout")
  @Log(title = "在线用户", action = BusinessType.FORCE)
  @PostMapping("/forceLogout")
  @ResponseBody
  public AjaxResult forceLogout(String sessionId) {
    try {
      Session session = sessionDAO.readSession(sessionId);
    } catch (UnknownSessionException e) {
      return error("用户已下线");
    }


    if(sessionId.equals(ShiroUtils.getSessionId())) {
      return error("当前登陆用户无法强退");
    }
    sessionService.forceLogout(sessionId);
    return success();
  }

}
